<template>
  <div>
    <div class="official_wrap gl_mb_20">
      <van-checkbox-group v-model="officialDataModal">
        <van-cell-group v-for="(item, index) in MemberDataForm" :key="index">
          <div class="official_title">{{ item.title }}</div>
          <van-cell v-for="(jtem, jndex) in item.children" :key="jndex" clickable @click="toggleCheckbox(jtem ,index, jndex)">
            <template #title>
              <div class="gl_clear">
                <van-checkbox :ref="'checkboxes' + index + jndex" class="gl_mt_10 gl_mr_10 gl_fl" :name="jtem" icon-size="16px" shape="square" />
                <van-image class="gl_fl" :src="getStaticFileUrl(jtem.imagePath)" radius="4px" fit="contain" width="40px" height="40px">
                  <template v-slot:error>
                    <van-image width="40px" height="40px" fit="contain" :src="defaultPhoto" />
                  </template>
                </van-image>
                <span class="official_name gl_fl">{{ jtem.name }}</span>
              </div>
            </template>
          </van-cell>
          <div v-if="!item.children.length" class="noConfirmInfo">
            <span>暂无该角色人员可以选择</span>
          </div>
        </van-cell-group>
      </van-checkbox-group>
    </div>

    <!-- 步骤按钮 -->
    <van-row gutter="10" class="bottom_btn_position">
      <van-col span="12" align="center">
        <van-button type="default" block @click="clickPrevStep()">上一步</van-button>
      </van-col>
      <van-col span="12" align="center">
        <van-button type="info" block :loading="btnLoading" @click="submitOfficial()">下一步</van-button>
      </van-col>
    </van-row>

    <!-- 个人 => 选择人员(裁判、领队)弹窗 -->
    <van-popup v-model="dialogVisibleForChoose" position="right" :style="{ width: '100%',height: '100%' }">
      <van-nav-bar class="main_header" title="请选择教练或领队">
        <template #left>
          <span @click="dialogVisibleForChoose = false">返回</span>
        </template>
        <template #right>
          <span @click="clickChooseOfficialOutbtn">确定</span>
        </template>
      </van-nav-bar>
      <modal-by-choose-official ref="refModalByChooseOfficial" :is-show="dialogVisibleForChoose" :dict="dict" :choose-official-loading="chooseOfficialLoading" @onSubmitChooseOfficial="submitChooseOfficial" />
    </van-popup>

    <!-- 团体 => 添加人员(裁判、领队)弹窗 -->
    <van-popup v-model="dialogVisibleForPersonal" get-container="#app" position="right" :style="{ width: '100%', height: '100%' }">
      <div class="add_member">
        <van-nav-bar class="main_header" title="编辑">
          <template #left>
            <span @click="dialogVisibleForPersonal = false">返回</span>
          </template>
          <template #right>
            <span @click="submitPersonalInfo">确定</span>
          </template>
        </van-nav-bar>
        <div class="add_member_content">
          <personal-info ref="refPersonalInfo" :user-data="createRegisterInput" :is-default-check="createRegisterInput.isApproved" :filter-tags="['Athlete']" :is-show-tag="true" />
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import defaultPhoto from '@/assets/images/face_default.png';
import { deepCopy } from '@/lib';
import { CopyData } from '@/lib';

import {
  api_GET_EventsManagementRegister, // 查询注册列表
  api_POST_EventsManagementRegisterWithtags, // 添加会员 多选标签
  api_GET_EventsManagementRegisterByIdCard,
  api_POST_EventsManagementEntryCompetitionOfficial // 2-2添加教练领队报项（如果已存在报名则可以添加，否则不成功）
} from '@/extend/api/gameswaggerApi/app';

import {
  SiSTKWEventsManagementCreateRegisterWithTagsInput
} from '@/lib/form/game/swaggerForm';

import { MemberDataForm } from '@/lib/form/home/enter/member';

import ModalByChooseOfficial from './modalByChooseOfficial';

import personalInfo from '@/viewMobile/components/PersonalInfo';

export default {
  components: {
    personalInfo,
    ModalByChooseOfficial
  },
  props: {
    // 当前用户信息
    userInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    // 当前用户信息
    userTeamInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    requiredIdData: {
      type: Object,
      default () {
        return {};
      }
    },
    isShow: {
      type: Boolean
    },
    // 字典信息
    dict: {
      type: Object,
      default () {
        return {};
      }
    },
    // 字典信息
    district: {
      type: Array,
      default () {
        return [];
      }
    },
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    // 通过点击个人或团体传进来的状态
    currentUserType: {
      type: String,
      default: ''
    },
    attachOfficial: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data () {
    return {
      show: false,
      loading: false,
      btnLoading: false,
      defaultPhoto: defaultPhoto,
      MemberDataForm: new MemberDataForm(),
      personList: [], // 获取到的人员数据
      activePersonData: {},
      officialDataModal: [], // 官员绑定的v-modal
      officialData: [], // 传递出去的官员数据
      chooseOfficialLoading: false,
      dialogVisibleForChoose: false, // 选择人员弹窗显示隐藏
      dialogVisibleForPersonal: false, // 添加人员弹窗显示隐藏
      createRegisterInput: new SiSTKWEventsManagementCreateRegisterWithTagsInput() // 添加人员vo
    };
  },
  watch: {
    isShow: {
      immediate: true,
      deep: true,
      handler: function(val) {
        if (val) {
          this.activePersonData = {};
          this.officialData = [];
          this.personList = [];
          this.$emit('onChangeOfficialData', this.officialData);
          this.api_GET_EventsManagementRegister();
        }
      }
    },
    dialogVisibleForPersonal(val) {
      if (!val) {
        // this.$refs.refPersonalInfo.clearInsideUserData();
        this.createRegisterInput = new SiSTKWEventsManagementCreateRegisterWithTagsInput();
      }
    }
  },
  methods: {
    // 点击行也可以选中复选框
    toggleCheckbox (data, key, jndex) {
      if (data.isActive) {
        for (let i = 0; i < this.officialData.length; i++) {
          const item = this.officialData[i];
          if (item.officialId === data.id && item.officialTagCode === key) {
            this.officialData.splice(i, 1);
            break;
          }
        }
      } else {
        this.officialData.push({
          officialId: data.id,
          officialTagCode: key
        });
      }
      this.$set(data, 'isActive', !data.isActive);
      this.$refs['checkboxes' + key + jndex][0].toggle();
    },
    // 点击添加人员按钮
    clickAddOfficial () {
      console.log('clickAddOfficial -> clickAddOfficial');
      this.dialogVisibleForPersonal = true;
    },
    clickChooseOfficial () {
      this.dialogVisibleForChoose = true;
    },
    // 查询注册列表
    api_GET_EventsManagementRegister() {
      // 如果 requiredIdData.delegationId 为 null 表示这个人没有加入团体，需先加入一个团体
      if (this.requiredIdData.delegationId) {
        this.loading = true;
        api_GET_EventsManagementRegister({ DelegationId: this.requiredIdData.delegationId, IncludeTags: true })
          .then(
            res => {
              this.personList = res.items;
              this.formatOfficialList();
              this.loading = false;
            }
          )
          .catch(
            error => {
              console.log(error);
              this.$toast({ type: 'fail', message: '查询注册列表失败' });
            }
          );
      } else {
        this.formatOfficialList();
      }
    },
    // 将获取到和现有的教练领队数据处理为页面需要的数据
    formatOfficialList () {
      this.MemberDataForm = new MemberDataForm();
      let dataList = deepCopy(this.personList);

      // 将获取到的官员列表以ID为KEY处理成对象，方便去重
      const _dataListMap = {};
      dataList.forEach(item => {
        _dataListMap[item.id] = item;
      });

      // 如果时非团体报名，那么需要关联已有的附加官员列表
      if (this.currentUserType !== 'Delegation') {
        const _concatList = [];
        // 附加的官员列表与获取到的官员列表做匹配，进行去重，以获取到的为主
        this.attachOfficial.forEach(item => {
          if (!(item.id in _dataListMap)) {
            _concatList.push(item);
          }
        });
        dataList = dataList.concat(_concatList);
      }

      if (dataList.length > 0) {
        // 聚合数据前提取共同的属性
        dataList.forEach(item => {
          for (const k in item.registerTags) {
            const ktem = item.registerTags[k];
            const _key = ktem.registerTagTypeCode;
            if (_key in this.MemberDataForm) {
              const deepItem = deepCopy(item);
              this.MemberDataForm[_key].children.push(deepItem);
            }
          }
        });
      }
    },
    // 提交个人信息
    submitPersonalInfo() {
      this.$refs.refPersonalInfo.getInsideUserData()
        .then(
          res => {
            if (res.imagePath) {
              CopyData(res, this.createRegisterInput);
              this.createRegisterInput.registerTypeCode = 'I';
              this.createRegisterInput.isCurrentUser = false;
              this.createRegisterInput.joinCurrentDelegation = true;
              this.apiRegisterWithTags();
            } else {
              this.$toast({ type: 'fail', message: `请上传头像` });
            }
          }
        );
    },
    apiRegisterWithTags () {
      api_POST_EventsManagementRegisterWithtags(this.createRegisterInput)
        .then(
          res => {
            this.api_GET_EventsManagementRegister();
            this.$toast({ type: 'success', message: '添加成功' });
            this.dialogVisibleForPersonal = false;
          }
        )
        .catch(
          error => {
            this.$toast({ type: 'fail', message: `添加失败 ${error.error.message}` });
          }
        );
    },
    // 外部确认按钮点击确定
    clickChooseOfficialOutbtn () {
      this.$refs.refModalByChooseOfficial.submitSelectTable();
    },
    // 确认选择教练或领队
    submitChooseOfficial (queryData) {
      this.chooseOfficialLoading = true;
      api_GET_EventsManagementRegisterByIdCard({
        idCardCode: queryData.idCardTypeCode,
        idCardNumber: queryData.idCardNumber,
        name: queryData.name,
        IncludeTags: true
      })
        .then(
          res => {
            const _tagList = res.registerTags;
            const _tagData = _tagList.find(item => item.registerTagTypeCode === queryData.registerTagTypeCode);
            if (_tagData) {
              // 重置数据中的registerTags 为找到的数据
              res.registerTags = [_tagData];
              this.$emit('onAddAttachOfficial', res);
              this.api_GET_EventsManagementRegister();
              this.dialogVisibleForChoose = false;
            } else {
              this.$toast({ type: 'fail', message: `【${queryData.name}】无【${queryData.registerTagTypeName}】身份，请检查信息填写是否准确` });
            }
            this.chooseOfficialLoading = false;
          }
        )
        .catch(
          error => {
            // 查询失败未找到
            this.$toast({ type: 'fail', message: `未查到【${queryData.name}】，请检查信息填写是否准确` });
            this.chooseOfficialLoading = false;
            console.log('submitChooseOfficial -> error', error);
          }
        );
    },
    // 点击执行上一步操作
    clickPrevStep () {
      this.$emit('onPrevStep');
    },
    submitOfficial () {
      if (!this.officialData.length) {
        this.$toast({ type: 'fail', message: '请至少选择一名教练或领队' });
        return;
      }
      const _hasCoachOrLeader = this.officialData.find(item => item.officialTagCode === 'Coach' || item.officialTagCode === 'Leader');
      if (_hasCoachOrLeader) {
        this.apiEntryCompetitionOfficial({
          competitionId: this.gameInfo.id,
          delegationId: this.requiredIdData.delegationId,
          registerId: this.requiredIdData.registerId,
          officials: this.officialData
        });
      } else {
        this.$toast({ type: 'fail', message: '请至少包含一名教练或领队' });
      }
    },
    apiEntryCompetitionOfficial (vo) {
      this.btnLoading = true;
      api_POST_EventsManagementEntryCompetitionOfficial(vo)
        .then(
          res => {
            this.btnLoading = false;
            this.$emit('onChangeOfficialData', this.officialData);
            this.clickNextStep();
          }
        )
        .catch(
          error => {
            this.btnLoading = false;
            this.$toast({ type: 'fail', message: `教练或领队提交失败 ${error.error.message}` });
          }
        );
    },
    // 点击执行下一步操作
    clickNextStep () {
      this.$emit('onNextStep');
    },
    errorPhoto() {
      return 'this.src="' + this.defaultPhoto + '";this.onerror=null;';
    },
    // 获取文件地址
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + '/' + relativeUrl;
    }
  }
};
</script>

<style lang="scss" scoped>
.official_name {
  display: inline-block;
  vertical-align: top;
  padding-left: 10px;
  line-height: 40px;
}

.official_title {
  font-size: 16px;
  // text-align: center;
  line-height: 40px;
  padding: 0 16px;
}
.official_wrap {
  position: relative;
}
.noConfirmInfo {
  width: 100%;
  text-align: center;
  padding: 20px 0;
  font-size: 14px;
  text-align: center;
  color: #aaa;
}

.add_member .add_member_content {
  position: absolute;
  top: 46px;
  bottom: 0;
  width: 100%;
  left: 0;
  overflow: auto;
}
</style>
